<template>
  <div>
    <el-breadcrumb separator="/" style="margin-bottom: 20px; margin-top: 20px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>促销活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>预售活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <div style="margin-bottom: 20px">
      <router-link :to="{'name': 'setUp' }">
        <el-button type="primary">创建预售活动</el-button>
      </router-link>
      <el-button style="margin-left: 20px" type="primary" @click="sort">预售排序</el-button>
    </div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="分公司" v-show="this.branchId === 1">
        <el-select v-model="formInline.branch" filterable clearable placeholder="请选择分公司">
          <el-option
            v-for="item in branchList"
            :label="item.branch_Name"
            :value="item.branch_Id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="formInline.status" filterable clearable>
          <el-option
            v-for="item in statusList"
            :label="item.preSaleStateName"
            :value="item.preSaleStateCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="预售商品名称">
        <el-input v-model="formInline.goodName"></el-input>
      </el-form-item>
      <el-form-item label="预售SKU编码">
        <el-input v-model="formInline.skuId"></el-input>
      </el-form-item>
      <el-form-item label="预售开始时间">
        <el-date-picker
          v-model="formInline.start"
          type="date"
          placeholder="选择开始日期"
          @change="startChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预售结束时间">
        <el-date-picker
          v-model="formInline.end"
          type="date"
          placeholder="选择结束日期"
          @change="endChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading.body="isLoading"
      :data="tableData"
      max-height="400"
      style="width: 100%"
      border>
      <el-table-column
        prop="productName"
        show-overflow-tooltip
        label="预售商品名称"
        align="center"
        min-width="120">
      </el-table-column>
      <el-table-column
        prop="productId"
        label="预售SKU编码"
        align="center"
        width="140">
      </el-table-column>
      <el-table-column
        prop="startTime"
        label="预售开始时间"
        align="center"
        min-width="150">
      </el-table-column>
      <el-table-column
        prop="endTime"
        label="预售结束时间"
        align="center"
        min-width="150">
      </el-table-column>
      <el-table-column
        prop="branchName"
        label="所属分公司"
        width="180"
        align="center">
      </el-table-column>
      <el-table-column
        prop="stateName"
        label="状态"
        align="center"
        width="120">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="280" >
        <template scope="scope">
          <el-button @click="handle(scope.$index, scope.row, $event)" size="small">详情</el-button>
          <el-button v-if="scope.row.stateName === '审核通过' || scope.row.stateName === '进行中'" @click="handle(scope.$index, scope.row, $event)" size="small">下线</el-button>
          <router-link :to="{name: 'edit', params: {row: scope.row}}">
            <el-button v-if="scope.row.stateName === '创建待审核'"  @click="handle(scope.$index, scope.row, $event)" size="small">编辑</el-button>
          </router-link>
          <el-button v-show="or_org_id === 347" v-if="scope.row.stateName === '创建待审核' || scope.row.stateName === '下线待审核'" @click="handle(scope.$index, scope.row, $event)" size="small">审核</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <el-pagination
      @current-change="handleCurrentChange"
      :page-size="Number(pageSize)"
      layout="total, prev, pager, next"
      :total="Number(total)"
      style="padding-top:10px;text-align: right;">
    </el-pagination>
    <!--详情弹窗-->
    <el-dialog title="活动详情" :visible.sync="detailDialog">
      <p style="height: 1px; background: black; margin-bottom: 0px"></p>
      <div class="shuoming">
          <pre style="margin: -10px">
          预售ID：{{detailData.id}}
          预售商品名称：{{detailData.productName}}
          预售SKU编码：{{detailData.productId}}
          预售开始时间：{{detailData.startTime}}
          预售结束时间：{{detailData.endTime}}
          配送开始时间：{{detailData.distributionStartTime}}
          配送结束时间：{{detailData.distributionEndTime}}
          活动说明：{{detailData.explain}}
          分公司：{{detailData.branchName}}
          一级客资类型：{{detailData.userTypes.join(',')}}
          创建人：{{detailData.createBy}}
          创建时间：{{detailData.createTime}}
          预售状态：{{detailData.state}}
          编辑人：{{detailData.editBy}}
          编辑时间：{{detailData.updateTime}}
          审核人：{{detailData.auditBy}}
          审核时间：{{detailData.auditTime}}
          不通过理由：{{detailData.discardReason}}
          </pre>
        <p style="height:1px; background:black; margin-top:0px"></p>
      </div>
    </el-dialog>
    <!--审核弹窗-->
    <el-dialog
      title="审核信息"
      v-model="dialogCheck">
      <p v-if="this.audit">您确定要审核该活动吗？</p>
      <p v-else>您确定要将活动下线吗？</p>
      <span>审核状态：</span>
      <template>
        <el-radio class="radio" v-model="radio" label="1">审核通过</el-radio>
        <el-radio class="radio" v-model="radio" label="2">不通过</el-radio>
      </template>
      <el-input v-show="this.radio === '2'" style="margin-top: 20px; width: 400px; display: block" v-model="noReason" placeholder="请输入不通过理由"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCheck = false">取 消</el-button>
        <el-button type="primary" @click="makeCheck">确 定</el-button>
      </span>
    </el-dialog>
    <!--排序弹窗-->
    <el-dialog
      title="预售排序"
      v-model="dialogSort">
      <el-table
        :data="SortData"
        max-height="400"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="70">
        </el-table-column>
        <el-table-column
          prop="productName"
          label="商品名称"
          show-overflow-tooltip
          align="center"
          width="160">
        </el-table-column>
        <el-table-column
          prop="startTime"
          label="开始时间"
          align="center"
          width="">
        </el-table-column>
        <el-table-column
          prop="state"
          label="状态"
          align="center"
          width="100">
        </el-table-column>
        <el-table-column
          label="操作"
          align="center">
          <template scope="scope">
            <el-button v-show="scope.$index !== 0" @click="top(scope.$index, scope.row)" size="small">置顶</el-button>
            <el-button v-show="scope.$index !== 0" @click="moveT(scope.$index, scope.row)" size="small">上移</el-button>
            <el-button @click="moveB(scope.$index, scope.row)" size="small">下移</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right; margin-top: 10px">
        <el-button @click="initial">按照开始先后顺序</el-button>
      </div>
      <div style="text-align: right; margin-top: 20px">
        <el-button @click="dialogSort = false">取消</el-button>
        <el-button @click="sure">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { cms } from '../../config/proxy.js'
  import { mapState } from 'vuex'
  import { apiURL } from '../../config/settings.js'
  export default {
    data () {
      return {
        formInline: {
          branch: '',
          skuId: '',
          goodName: '',
          start: '',
          end: '',
          status: ''
        },
        branchList: [],
        statusList: [],
        tableData: [],
        isLoading: false,
        total: '',
        pageSize: 10,
        currentPage: '',
//      详情弹窗
        detailData: '',
        detailDialog: false,
//      审核弹窗
        audit: false,
        dialogCheck: false,
        radio: '1',
        index: '',
        rowId: '',
        noReason: '',
//      排序弹窗
        dialogSort: false,
        SortData: []
      }
    },
    methods: {
      onSubmit () {
        console.log(this.or_org_id)
        this.tableData = []
        this.isLoading = true
        const queryData = {
          branchId: this.branchId === 1 ? this.formInline.branch : this.branchId,
          endTime: this.formInline.end,
          page: 1,
          pageSize: 10,
          productId: this.formInline.skuId,
          productName: this.formInline.goodName,
          startTime: this.formInline.start,
          state: this.formInline.status
        }
        console.log(queryData)
        cms.saleList(queryData, (res) => {
          console.log(res)
          setTimeout(() => {
            this.isLoading = false
          }, 500)
          if (res.message === 'ok') {
            this.tableData = res.content.content
            this.total = res.content.count
          } else {
            this.$message({
              showClose: true,
              message: '查询失败',
              type: 'error'
            })
          }
        })
      },
      handle (index, row, event) {
        this.rowId = row.id
        const handleName = event.target.innerText
        switch (handleName) {
          case '详情':
            apiURL.detail = '/preSale/preSaleDetail/' + row.id
            cms.detail({}, (res) => {
              console.log(res)
              if (res.message === 'ok') {
                this.detailData = res.content
                this.detailDialog = true
              } else {
                this.$message({
                  showClose: true,
                  message: '查看详情失败',
                  type: 'error'
                })
              }
            })
            break
          case '下线':
            this.$confirm('您确定要将活动下线吗, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
//            下线请求
              const offData = {
                preSaleId: row.id,
                editBy: this.userName
              }
              cms.off(offData, (res) => {
                if (res.message === 'ok') {
                  row.stateName = '下线待审核'
                  this.$message({
                    type: 'success',
                    message: '下线成功!'
                  })
                } else {
                  this.$message({
                    type: 'error',
                    message: '下线失败!'
                  })
                }
              })
            }).catch(() => {
            })
            break
          case '审核':
            this.radio = '1'
            this.audit = false
            if (row.stateName === '创建待审核') {
              this.audit = true
            }
            this.dialogCheck = true
            this.index = index
            break
        }
      },
      startChange (val) {
        this.formInline.start = val
      },
      endChange (val) {
        this.formInline.end = val
      },
//    审核请求
      makeCheck () {
//      发审核请求
        if (this.radio === '1') {
          const auditData = {
            preSaleId: this.rowId,
            auditBy: this.userName,
            departmentId: this.or_org_id
          }
          cms.check(auditData, (res) => {
            this.dialogCheck = false
            console.log(res)
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '请求成功'
              })
              this.tableData[this.index].stateName = '审核通过'
            } else {
              this.$message({
                type: 'error',
                message: '请求失败'
              })
            }
          })
        } else {
          const auditData = {
            preSaleId: this.rowId,
            auditBy: this.userName,
            departmentId: this.or_org_id,
            discardReason: this.noReason
          }
          console.log(auditData)
          cms.cancelCheck(auditData, (res) => {
            this.dialogCheck = false
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '请求成功'
              })
              this.tableData[this.index].stateName = '未通过'
            } else {
              this.$message({
                type: 'error',
                message: '请求失败'
              })
            }
          })
        }
      },
      handleCurrentChange (val) {
        this.tableData = []
        this.isLoading = true
        const queryData = {
          branchId: this.branchId === 1 ? this.formInline.branch : this.branchId,
          endTime: this.formInline.end,
          page: val,
          pageSize: 10,
          productId: this.formInline.skuId,
          productName: this.formInline.goodName,
          startTime: this.formInline.start,
          state: this.formInline.status
        }
        cms.saleList(queryData, (res) => {
          console.log(res)
          setTimeout(() => {
            this.isLoading = false
          }, 500)
          if (res.message === 'ok') {
            this.tableData = res.content.content
          } else {
            this.$message({
              showClose: true,
              message: '查询失败',
              type: 'error'
            })
          }
        })
      },
      top (index, row) {
        row.orderNum = 1
        this.SortData.splice(0, 0, row)
        this.SortData.splice(index + 1, 1)
        this.SortData.forEach(function (item, index) {
          if (index !== 0) {
            item.orderNum += 1
          }
        })
        console.log(this.SortData)
      },
      moveT (index, row) {
        var num = row.orderNum
        var _num = this.SortData[index - 1].orderNum
        row.orderNum = _num
        this.SortData[index - 1].orderNum = num
        this.SortData.splice(index - 1, 0, row)
        this.SortData.splice(index + 1, 1)
        console.log(this.SortData)
      },
      moveB (index, row) {
        var num = row.orderNum
        var _num = this.SortData[index + 1].orderNum
        row.orderNum = _num
        this.SortData[index + 1].orderNum = num
        this.SortData.splice(index + 2, 0, row)
        this.SortData.splice(index, 1)
      },
      sure () {
        console.log('排序')
        const dataArr = []
        this.SortData.forEach(function (item, index) {
          dataArr[index] = {
            preSaleId: item.id,
            orderNum: item.orderNum
          }
        })
        console.log(dataArr)
        cms.sort(dataArr, res => {
          if (res.message === 'ok') {
            this.$message({
              showClose: true,
              message: '排序成功',
              type: 'success'
            })
          } else {
            this.$message({
              showClose: true,
              message: '排序失败',
              type: 'error'
            })
          }
        })
      },
      initial () {
        this.SortData.forEach(function (item, index) {
          item.newTime = new Date(item.startTime).getTime()
        })
        this.SortData.sort(function (x, y) {
          return x.newTime - y.newTime
        })
      },
      sort () {
        this.dialogSort = true
        const Data = {
          branchId: this.branchId === 1 ? this.formInline.branch : this.branchId
        }
        console.log(Data)
        cms.sortList(Data, (res) => {
          console.log(res)
          this.SortData = res.content
        })
      }
    },
    computed: mapState({
      userId: function (state) {
        if (!state.user.info.branchId) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.branchId
      },
      userName: function (state) {
        if (!state.user.info.user_name) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.user_name
      },
      departmentId: function (state) {
        if (!state.user.info.or_org_id) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.or_org_id
      },
      branchId: function (state) {
        if (!state.user.info.branchId) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.branchId
      },
      or_org_id: function (state) {
        if (!state.user.info.or_org_id) {
          this.$store.dispatch('SET_TOKEN')
        }
        return state.user.info.or_org_id
      }
    }),
    created () {
      this.detailData = {
        userTypes: []
      }
//    分公司
      cms.getBranch({}, (res) => {
        if (res.message === 'ok') {
          this.branchList = res.content
        }
      })
//    状态
      cms.status({}, (res) => {
        if (res.message === 'ok') {
          this.statusList = res.content
        }
      })
    }
  }
</script>
<style>
  @media screen and (min-width:1000px) {
    .supplier-form{
      max-width: 600px;
    }
  }
  .el-form--inline div {
    display: inline-block;
    float: left;
  }
  .el-dialog__body {
    padding-top: 0;
  }
  .shuoming {
    line-height: 2;
    font-size: 16px;
    font-weight: 700;
    color: #1f2d3d;
  }
</style>
